var fs = require('fs');
var path = require('path');
var os = require('os');

var main = (function () {
    var self, config;
    return {
        init: function (opts) {
            self=this;
            config=opts;
            (async ()=>{
                self.compare(await self.read(config.src),await self.read(config.target));
            })();
        },
        read:(file)=>{
            return new Promise((resolve,reject)=>{
                fs.readFile(path.join(__dirname,file),'utf8',(err,txt)=>{
                    if(err)return reject(err);
                    resolve(txt);
                });
            }).catch(err=>{
                console.error('ERROR>>>:',err);
            });
        },
        compare:(srcLines,targetLines)=>{
            srcLines=srcLines.split(os.EOL+os.EOL);
            targetLines=targetLines.split(os.EOL+os.EOL);
            console.log('srcLines:',srcLines);
            console.log('targetLines:',targetLines);
            var diff=[];
            for(let line of srcLines){
                if(!~targetLines.indexOf(line))diff.push(line);
            }
            console.log('diff:\n',diff);
            self.save(diff);
        },
        save:(diff)=>{
            fs.writeFile(path.join(__dirname,path.basename(config.src,'.txt')+'==》'+path.basename(config.target,'.txt')+'--diff.txt'),diff.join('\n\r'),(err)=>{
                if(err)throw err;
                console.log('Diff saved.');
            });
        }
    }

})();

main.init({
        src:'JS.txt',
        target:'MEAN.txt'
    }
);